package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Entry.MaterialBorrowRecord;
import com.example.chamberlainserver.Entry.User;
import com.example.chamberlainserver.Service.MaterialBorrowRecordService;
import com.example.chamberlainserver.Service.UserService;
import com.example.chamberlainserver.Vo.Request.Material.MaterialBorrowDTO;
import com.example.chamberlainserver.Vo.Request.Material.MaterialBorrowQuery;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import com.example.chamberlainserver.dto.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * 物资外借记录控制器
 */
@RestController
@RequestMapping("/borrow")
public class MaterialBorrowRecordController {

    @Autowired
    private MaterialBorrowRecordService materialBorrowRecordService;
    
    @Autowired
    private UserService userService;

    /**
     * 添加物资外借记录
     * @param borrowDTO 物资外借记录DTO
     * @return 添加结果
     */
    @PostMapping("/add")
    public ResponseEntity<ApiResponse<MaterialBorrowRecord>> addBorrowRecord(@RequestBody MaterialBorrowDTO borrowDTO) {
        try {
            // 从SecurityContextHolder获取当前认证的用户名
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            // 获取当前用户信息
            User user = userService.getUserByStuNo(username);
            
            if (user == null) {
                return ResponseEntity.ok(ApiResponse.error("未获取到当前登录用户信息"));
            }
            
            // 设置操作人ID
            borrowDTO.setBorrowOperatorId(user.getId());
            
            MaterialBorrowRecord record = materialBorrowRecordService.addBorrowRecord(borrowDTO);
            return ResponseEntity.ok(ApiResponse.success("添加物资外借记录成功", record));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.ok(ApiResponse.error(e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("添加物资外借记录失败: " + e.getMessage()));
        }
    }

    /**
     * 更新物资外借记录
     * @param borrowDTO 物资外借记录DTO
     * @return 更新结果
     */
    @PutMapping("/update")
    public ResponseEntity<ApiResponse<MaterialBorrowRecord>> updateBorrowRecord(@RequestBody MaterialBorrowDTO borrowDTO) {
        try {
            MaterialBorrowRecord record = materialBorrowRecordService.updateBorrowRecord(borrowDTO);
            return ResponseEntity.ok(ApiResponse.success("更新物资外借记录成功", record));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.ok(ApiResponse.error(e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新物资外借记录失败: " + e.getMessage()));
        }
    }

    /**
     * 删除物资外借记录
     * @param id 记录ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteBorrowRecord(@PathVariable Long id) {
        try {
            boolean success = materialBorrowRecordService.deleteBorrowRecord(id);
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("删除物资外借记录成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("删除物资外借记录失败，记录不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除物资外借记录失败: " + e.getMessage()));
        }
    }

    /**
     * 根据ID查询物资外借记录
     * @param id 记录ID
     * @return 物资外借记录
     */
    @GetMapping("/get/{id}")
    public ResponseEntity<ApiResponse<MaterialBorrowRecord>> getBorrowRecordById(@PathVariable Long id) {
        try {
            MaterialBorrowRecord record = materialBorrowRecordService.getBorrowRecordById(id);
            if (record != null) {
                return ResponseEntity.ok(ApiResponse.success("查询物资外借记录成功", record));
            } else {
                return ResponseEntity.ok(ApiResponse.error("物资外借记录不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询物资外借记录失败: " + e.getMessage()));
        }
    }

    /**
     * 分页查询物资外借记录
     * @param query 查询条件
     * @return 分页结果
     */
    @PostMapping("/page")
    public ResponseEntity<ApiResponse<PageResult<MaterialBorrowRecord>>> pageBorrowRecords(@RequestBody MaterialBorrowQuery query) {
        try {
            PageResult<MaterialBorrowRecord> pageResult = materialBorrowRecordService.pageBorrowRecords(query);
            return ResponseEntity.ok(ApiResponse.success("查询物资外借记录成功", pageResult));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.ok(ApiResponse.error(e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询物资外借记录失败: " + e.getMessage()));
        }
    }

    /**
     * 归还物资
     * @param id 记录ID
     * @param isIntact 是否完好
     * @param remark 备注
     * @return 更新结果
     */
    @PutMapping("/return/{id}")
    public ResponseEntity<ApiResponse<MaterialBorrowRecord>> returnMaterial(
            @PathVariable Long id,
            @RequestParam Boolean isIntact,
            @RequestParam(required = false) String remark) {
        try {
            MaterialBorrowRecord record = materialBorrowRecordService.returnMaterial(id, isIntact, remark);
            return ResponseEntity.ok(ApiResponse.success("归还物资成功", record));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.ok(ApiResponse.error(e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("归还物资失败: " + e.getMessage()));
        }
    }
}